#import <QTKit/QTKit.h>
#import <dispatch/dispatch.h>
#import "ORGSSAudioImplementation.h"

static QTMovie *bgm, *bgs, *me, *se;

static void play_sound ( QTMovie **, char *, size_t, float, float );
static void stop_sound ( QTMovie ** );

static void play_sound ( QTMovie **soundPtr, char *name, size_t name_len, float volume, float pitch ) {
	stop_sound(soundPtr);
	
	NSString *aString = [[NSString alloc] initWithBytes: name length: name_len encoding: NSASCIIStringEncoding];
	NSError *error;
	
	*soundPtr = [[QTMovie movieWithFile: aString error: &error] retain];
	[aString release];
	
	[*soundPtr play];
	
	if ( error != nil ) {
		NSLog(@"%@\n", error);
	}
}

static void stop_sound ( QTMovie **soundPtr ) {
	if ( *soundPtr != nil ) {
		[*soundPtr stop];
		[*soundPtr release];
		*soundPtr = nil;
	}
}

VALUE ORGSSPlayBGM ( VALUE self, VALUE name, VALUE volume, VALUE pitch ) {
	play_sound(&bgm, RSTRING(name)->ptr, RSTRING(name)->len, (float) NUM2DBL(volume), NUM2DBL(pitch));
	
	return Qnil;
}

VALUE ORGSSStopBGM ( VALUE self ) {
	stop_sound(&bgm);
	
	return Qnil;
}

VALUE ORGSSPlayBGS ( VALUE self, VALUE name, VALUE volume, VALUE pitch ) {
	play_sound(&bgs, RSTRING(name)->ptr, RSTRING(name)->len, (float) NUM2DBL(volume), NUM2DBL(pitch));
	
	return Qnil;
}

VALUE ORGSSPlayME ( VALUE self, VALUE name, VALUE volume, VALUE pitch ) {
	play_sound(&me, RSTRING(name)->ptr, RSTRING(name)->len, (float) NUM2DBL(volume), NUM2DBL(pitch));
	
	return Qnil;
}

VALUE ORGSSPlaySE ( VALUE self, VALUE name, VALUE volume, VALUE pitch ) {
	play_sound(&se, RSTRING(name)->ptr, RSTRING(name)->len, (float) NUM2DBL(volume), NUM2DBL(pitch));
	
	return Qnil;
}

VALUE ORGSSStopSE ( VALUE self ) {
	stop_sound(&se);
	
	return Qnil;
}